package com.planshare.activity;

import java.net.MalformedURLException;
import java.net.URL;

import org.json.rpc.client.HttpJsonRpcClientTransport;
import org.json.rpc.client.JsonRpcInvoker;

import com.planshare.object.AndroidPlan;
import com.planshare.service.UserService;
import com.planshare.util.UserUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyPlansActivity extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final LinearLayout as = new LinearLayout(MyPlansActivity.this);
		as.setOrientation(LinearLayout.VERTICAL);
		this.setContentView(as);
		final ProgressDialog dialog = new ProgressDialog(MyPlansActivity.this);
		dialog.setMessage("Retrieving data from server...");
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		dialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				
				if (UserUtil.userPlans == null) {
					getPlansForUser();
				}

				MyPlansActivity.this.runOnUiThread(new Runnable() {
					public void run() {

						for (final AndroidPlan plan : UserUtil.userPlans) {
							// Create the text view
							TextView textView = new TextView(MyPlansActivity.this);
							textView.setTextSize(16);
							textView.setText(plan.getName());
							textView.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									UserUtil.planViewed = plan;
									Intent intent = new Intent(MyPlansActivity.this,
											ViewPlanActivity.class);
									startActivity(intent);
								}
							});

							as.addView(textView);
							
							TextView textViewLocation = new TextView(MyPlansActivity.this);
							textViewLocation.setTextSize(10);
							textViewLocation.setText(plan.getLocation() + " - " + plan.getDate().toString());
							
							as.addView(textViewLocation);
							
							TextView gap = new TextView(MyPlansActivity.this);
							gap.setTextSize(5);
							gap.setText("");
							
							as.addView(gap);
						}

						dialog.dismiss();
					}
				});
			}
		}).start();
	}

	private void getPlansForUser() {
		HttpJsonRpcClientTransport transport;
		try {
			transport = new HttpJsonRpcClientTransport(new URL(UserUtil.userServiceUrl));
			JsonRpcInvoker invoker = new JsonRpcInvoker();
			UserService calc = invoker.get(transport, "user", UserService.class);

			UserUtil.userPlans = calc.getPlansForUser(UserUtil.user);
			System.out.println(UserUtil.userPlans.length);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
